let tabs;
let data;
let requestUrl;
let loginPage = "/login.html";

let hideIds = [];
let displayIds = [];

/**
 * 往localStorage中添加指定的tab
 * @param tab
 */
function addToTabs(tab) {
	if (!tabs) {
		tabs = [];
	}

	// 数组不存在才添加
	let exists = tabs.some(function (item) {
		return tab.title === item.title;
	});
	if (!exists) {
		tabs.push(tab);
	}

	setCurrent(tab.title);

	localStorage.setItem("mhxysy:tabs", JSON.stringify(tabs));
}

/**
 * 从localStorage中删除指定标题的tab
 * @param title
 */
function deleteFromTabs(title) {
	tabs = tabs.filter(function (item) {
		return item.title !== title;
	});

	localStorage.setItem("mhxysy:tabs", JSON.stringify(tabs));
}

/**
 * 获取所有打开的tab
 */
function getTabs() {
	let tabs = localStorage.getItem("mhxysy:tabs");

	return JSON.parse(tabs);
}

/**
 * 获取当前选中的tab
 */
function getCurrent() {
	return localStorage.getItem("mhxysy:currTab");
}

/**
 * 设置当前选中的tab
 */
function setCurrent(title) {
	// 删除左侧菜单的客户端缓存
	localStorage.setItem("mhxysy:currTab", title);
}

/**
 * 初始化左侧菜单
 */
function InitLeftMenu() {
	let menus = localStorage.getItem("mhxysy:leftMenus");
	let leftMenus;

	if (menus) {
		leftMenus = JSON.parse(menus);

		fetchLeftMenus();
	} else {
		ajaxGet("/menu/getLeftMenu", {}, function(response) {
			leftMenus = response.data;

			fetchLeftMenus();

			localStorage.setItem("mhxysy:leftMenus", JSON.stringify(leftMenus));
		}, error);
	}

	/**
	 * 初始化左侧菜单
	 */
	function fetchLeftMenus () {
		$("#nav").accordion({
			fit: true,
			border: false,
			animate: true,
			onSelect: function (title, index) {
				// let data = {
				// 	"index": index,
				// 	"title": title
				// };
				//
				// console.log("选中面板：" + index + " => " + title);
			}
		});

		$.each(leftMenus, function(i, node) {
			let menus = "<ul>";

			$.each(node.children, function(j, child) {
				menus += "<li>";
				menus += 	"<div>";
				menus += 		"<a ref='" + child.id + "' href='javascript:void(0)' rel='" + child.url + "' >";
				menus += 			"<span class='icon " + child.iconClass + "' >&nbsp;</span>";
				menus += 			"<span class='nav'>" + child.name + "</span>";
				menus += 		"</a>";
				menus += 	"</div>";
				menus += "</li>";
			});

			menus += "</ul>";

			$("#nav").accordion("add", {
				title: node.name,
				content: menus,
				iconCls: "icon " + node.iconClass
			});
		});

		$(".easyui-accordion li a").on("click", function() {
			let url = $(this).attr("rel");
			let title = $(this).children(".nav").text();
			let iconClass = $(this).children(".icon").attr("class");

			addTab(title, url, iconClass);

			$(".easyui-accordion li div").removeClass("selected");

			$(this).parent().addClass("selected");
		}).hover(function() {
			$(this).parent().addClass("hover");
		}, function() {
			$(this).parent().removeClass("hover");
		});
	}
}

function addTab(title, url, iconClass = "") {
	let $tabs_ = $("#tabs");
	let exists = $tabs_.tabs("exists", title);

	if (!exists) {
		$tabs_.tabs("add", {
			title: title,
			icon: iconClass,
			closable: true,
			content: createFrame(url)
		});

		addToTabs({
			title: title,
			url: url
		});
	} else {
		$tabs_.tabs("select", title);
		$("#mm-tabupdate").click();
	}

	tabClose();
}

function createFrame(url) {
	return "<iframe style='width:100%;height:98%;scroll-behavior:auto;border:0;' src='" + url + "'></iframe>";
}

function tabClose() {
	// 为选项卡绑定右键
	$("#tabs ul li .tabs-inner").bind("contextmenu", function(e) {
		e.preventDefault();

		$("#tabs-right-menu").menu("show", {
			left: e.pageX,
			top: e.pageY
		});

		let title = $(this).children(".tabs-closable").text();

		setCurrent(title);

		$("#tabs").tabs("select", title);
	}).dblclick(function() { // 双击关闭TAB选项卡
		let currTab = $(this).children(".tabs-closable").text();

		$("#tabs").tabs("close", currTab);

		deleteFromTabs(currTab);
	});
}

/**
 * 绑定右键菜单事件
 */
function tabCloseEven() {
	let _tabs = $("#tabs");

	// 刷新
	$("#mm-tabupdate").click(function() {
		let currTab = _tabs.tabs("getSelected");
		let url = $(currTab.panel("options").content).attr("src");

		_tabs.tabs("update", {
			tab: currTab,
			options: {
				content: createFrame(url)
			}
		})
	});

	// 关闭当前
	$("#mm-tabclose").click(function() {
		let title = getCurrent();

		deleteFromTabs(title);
		_tabs.tabs("close", title);
	});

	// 全部关闭
	$("#mm-tabcloseall").click(function() {
		$(".tabs-inner > span.tabs-closable").each(function(i, n) {
			let title = $(n).text();

			deleteFromTabs(title);
			_tabs.tabs("close", title);
		});
	});

	// 关闭除当前之外的TAB
	$("#mm-tabcloseother").click(function() {
		$("#mm-tabcloseright").click();
		$("#mm-tabcloseleft").click();
	});

	// 关闭当前左侧的TAB
	$("#mm-tabcloseleft").click(function() {
		let prevAll = $(".tabs-selected").prevAll();

		if(prevAll.length > 0) {
			prevAll.each(function(i, n) {
				let title = $("span.tabs-inner:eq(0) span.tabs-closable", $(n)).text();

				deleteFromTabs(title);
				_tabs.tabs("close", title);
			});
		}
	});

	// 关闭当前右侧的TAB
	$("#mm-tabcloseright").click(function() {
		let nextAll = $(".tabs-selected").nextAll();

		if(nextAll.length > 0) {
			nextAll.each(function(i, n) {
				let title = $("span.tabs-inner:eq(0) span.tabs-closable", $(n)).text();

				deleteFromTabs(title);
				_tabs.tabs("close", title);
			});
		}
	});
}

/**
 * 设置排序
 */
function setSort() {
	$.messager.prompt("设置菜单排序", "请输入排序号", function(pxh) {
		if (pxh) {
			let data = $("#menu_tree").tree("getSelected");

			if (data) {
				ajaxPost("/user_menu/updateSort", {
					menuId: data.id,
					pxh: pxh
				}, function (res) {
					showMsg(res.message);

					$("#menu_tree").tree("reload");

					// 删除左侧菜单的客户端缓存
					localStorage.removeItem("mhxysy:leftMenus");
				}, error);
			}
		}
	});
}

/**
 * 折叠全部
 * @param selector 选择器
 */
function collapseAll(selector) {
	$(selector).tree("collapseAll");
}

/**
 * 展开全部
 * @param selector 选择器
 */
function expandAll(selector) {
	$(selector).tree("expandAll");
}

/**
 * 保存菜单树的修改
 */
function saveChange() {
	// 任意数组不为空时才发送ajax请求
	if (displayIds.length > 0 || hideIds.length > 0) {
		ajaxPost("/user_menu/control", {
			displayIds: JSON.stringify(displayIds),
			hideIds: JSON.stringify(hideIds)
		}, function (resp) {
			hideIds = [];
			displayIds = [];

			showMsg(resp.message);

			$("#menu_tree").tree("reload");

			// 删除左侧菜单的客户端缓存
			localStorage.removeItem("mhxysy:leftMenus");
		}, error);
	}

	$("#system_window").dialog("close");
}

/**
 * 启用邮箱
 * @param id 邮箱ID
 */
function enable(id) {
	ajaxPost("/email/enable", {
		id: id,
		state: 1
	}, function (resp) {
		showMsg(resp.message);

		$("#email_list").datagrid("reload");
	}, error);
}

function checkNode(checked, menuId) {
	if (checked) {
		if (displayIds.length === 0 || displayIds.indexOf(menuId) === -1) {
			displayIds.push(menuId);
		}

		if (hideIds.length > 0) {
			for (let i = 0; i < hideIds.length; i++) {
				if (hideIds[i] === menuId) {
					hideIds.splice(i, 1);
				}
			}
		}
	} else {
		if (hideIds.length === 0 || hideIds.indexOf(menuId) === -1) {
			hideIds.push(menuId);
		}

		if (displayIds.length > 0) {
			for (let i = 0; i < displayIds.length; i++) {
				if (displayIds[i] === menuId) {
					displayIds.splice(i, 1);
				}
			}
		}
	}
}

$(function() {

	tabClose();
	tabCloseEven();
	InitLeftMenu();

	ajaxGet("/user/getLogin", {}, function(resp) {
		let data = resp.data;

		$("#loginName").html(data.name);
	}, error);

	$("#tabs").tabs("add", {
		title: "欢迎使用",
		icon: "",
		closable: false,
		content: createFrame("/main.html")
	});

	/******************************************************************************************************/

	/**
	 * 更多设置
	 */
	$("#more").menubutton({
		title: "更多设置",
		menu: "#more-menu"
	});

	/**
	 * 系统设置
	 */
	$("#sys_set").on("click", function() {
		ajaxGet("/user/getLogin", {},function(response) {
			let data = response.data;

			$("#username").textbox("setValue", data.username);
		}, error);

		$("#user_details").propertygrid("reload");
		$('#user_details').propertygrid("expandGroup");

		$("#system_window").dialog("open");
	});

	/**
	 * 清理缓存
	 */
	$("#clean").on("click", function() {
		ajaxPost("/cache/clean", {},function(resp) {
			showMsg(resp.message);

			localStorage.clear();
		}, error);
	});

	/**
	 * 安全退出
	 */
	$("#logout").on("click", function() {
		$.messager.confirm("系统提示", "您确定要退出本次登录吗?", function(bool) {
			if (bool) {
				ajaxPost("/user/logout", {}, function() {
					location.href = loginPage;
				}, error);
			}
		});
	});

	/**
	 * 接口文档
	 */
	$("#doc").on("click", function() {
		location.href = "/doc.html";
	});

	/**
	 * 初始化权限
	 */
	$("#init").on("click", function() {
		ajaxPost("/permission/resources", {}, function(resp) {
			showMsg(resp.message);
		}, error);
	});

	/******************************************************************************************************/

	$("#sys_tabs").tabs({
		fit: true,
		pill: true,
		narrow: false,
		border: false,
		closable: false,
		justified: true,
		showHeader: true
	});

	$("#user_details").propertygrid({
		url: "/user/selectUserDetails",
		width: 598,
		height: 360,
		showGroup: true,
		scrollbarSize: 0,
		onAfterEdit: function (rowIndex, rowData, changes) {
			if (changes.name) {
				let params = {};
				let name = rowData.name;

				params[name] = changes.value;

				ajaxPost("/user/update", params, function (resp) {
					showMsg(resp.message);
				}, error);
			}
		}
	});

	$("#email_list").datagrid({
		url: "/email/selectByUserId",
		method: "get",
		height: 360,
		fitColumns: true,
		rownumbers: true,
		toolbar: [{
			iconCls: "icon-add",
			text: "添加",
			handler: function() {
				requestUrl = "/email/insert";

				ajaxPost(requestUrl, {
					state: 0,
					account: "xxxxx@163.com"
				}, function () {
					$("#email_list").datagrid("reload");
				}, error);
			}
		}, "-", {
			iconCls: "icon-edit",
			text: "修改",
			handler: function() {
				let datagrid = $("#email_list");
				let row = datagrid.datagrid("getSelected");
				let rowIndex = datagrid.datagrid("getRowIndex", row);
				let editingId = localStorage.getItem("mhxysy:editingId");

				if (editingId && parseInt(editingId) !== rowIndex) {
					datagrid.datagrid("selectRow", editingId);
				} else {
					if (row) {
						localStorage.setItem("mhxysy:editingId", rowIndex);

						requestUrl = "/email/updateById";

						datagrid.datagrid("beginEdit", rowIndex);
					} else {
						alertMsg("请选择要修改的记录", "warning");
					}
				}
			}
		}, "-", {
			iconCls: "icon-save",
			text: "保存",
			handler: function() {
				let editingId = localStorage.getItem("mhxysy:editingId");

				if (editingId) {
					// 只有结束编辑才能获取到最新的值
					$("#email_list").datagrid("endEdit", editingId);

					ajaxPost(requestUrl, data, function (res) {
						showMsg(res.message);

						localStorage.removeItem("mhxysy:editingId");

						$("#email_list").datagrid("reload");
					}, error);
				}
			}
		}, "-", {
			iconCls: "icon-cancel",
			text: "取消",
			handler: function() {
				let editingId = localStorage.getItem("mhxysy:editingId");

				if (editingId) {
					$("#email_list").datagrid("cancelEdit", editingId);

					localStorage.removeItem("mhxysy:editingId");
				}
			}
		}, "-", {
			iconCls: "icon-delete",
			text: "删除",
			handler: function() {
				let datagrid = $("#email_list");
				let row = datagrid.datagrid("getSelected");

				if (row) {
					$.messager.confirm("提示", "是否确认删除？", function(bool) {
						if(bool) {
							let rowIndex = datagrid.datagrid("getRowIndex", row);

							ajaxPost("/email/deleteById", {
								id: row.id
							}, function (res) {
								showMsg(res.message);

								datagrid.datagrid("deleteRow", rowIndex);
							}, error);
						}
					});
				} else {
					alertMsg("请选择要删除的记录", "warning");
				}
			}
		}],
		onAfterEdit: function (rowIndex, rowData, changes) {
			data = {
				id: rowData.id,
				state: changes.state ? changes.state : rowData.state,
				account: changes.account ? changes.account : rowData.account
			};
		},
		columns: [[
			{field: "id", title: "编号", align:"center", hidden: true},
			{field: "account", title: "邮箱账号", align:"center", width: 200, editor: "textbox"},
			{field: "state", title: "启用状态", align:"center", width: 100
				, editor: {
					type: "combobox",
					options: {
						url: "/json/states.json",
						panelHeight: "auto",
						formatter: function(row) {
							return "<img width='20' src='" + row.icon + "' />&nbsp;" + row.text;
						}
					}
				}, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/json/states.json",{}, function (resp) {
						let data = resp.data;
						let state = data[value];

						$("#state_" + rowIndex).attr("src", state.icon).attr("title", state.text);
					});

					return "<img id='state_" + rowIndex + "' />";
				}
			},
			{field: "operation", title: "操作", align:"center", width: 50
				, formatter: function(value, rowData, rowIndex) {
					if (rowData.state === 0) {
						return "<button type='button' onclick='enable(" + rowData.id + ")'>启用</button>";
					} else {
						return "<div>-</div>";
					}
				}
			}
		]]
	});

	$("#menu_tree").tree({
		url: "/menu/getMenuTree",
		method: "get",
		lines: true,
		animate: true,
		checkbox: true,
		onlyLeafCheck: false,
		formatter:function(node) {
			if (node.pxh != null) {
				return node.text + "[" + node.pxh + "]";
			} else {
				return node.text;
			}
		},
		onContextMenu: function(e, node) {
			e.preventDefault();

			if (!node.children) {
				// 选中该树节点
				$("#menu_tree").tree("select", node.target);

				// 显示右键菜单
				$("#menu_tree-right-menu").menu("show", {
					left: e.pageX,
					top: e.pageY
				});
			}
		},
		onCheck: function (node, checked) {
			let children = node.children;

			// 父节点点击复选框
			if (children && children.length > 0) {
				for (let i = 0; i < children.length; i++) {
					checkNode(checked, children[i].id);
				}
			} else {
				checkNode(checked, node.id);
			}
		}
	});

	$("#system_window").dialog({
		title: "系统设置",
		modal: true,
		closed: true,
		closable: true,
		draggable: false,
		buttons: [{
			iconCls: "icon-ok",
			text: "确定",
			handler: function() {
				saveChange();
			}
		}]
	});

	/******************************************************************************************************/

	/**
	 * password_form
	 */
	// 用户名
	$("#username").textbox({
		width: 150,
		editable: false
	});

	// 旧密码
	$("#oldPass").passwordbox({
		width: 150,
		required: true,
		inputEvents: $.extend({}, $.fn.passwordbox.defaults.inputEvents, {
			keypress: function(e) {
				let char = String.fromCharCode(e.which);

				$("#viewer").html(char).fadeIn(200, function() {
					$(this).fadeOut();
				});
			}
		})
	});

	// 新密码
	$("#password").passwordbox({
		width: 150,
		required: true,
		inputEvents: $.extend({}, $.fn.passwordbox.defaults.inputEvents, {
			keypress: function(e) {
				let char = String.fromCharCode(e.which);

				$("#viewer").html(char).fadeIn(200, function() {
					$(this).fadeOut();
				});
			}
		})
	});

	// 确认密码
	$("#rePass").passwordbox({
		width: 150,
		required: true,
		inputEvents: $.extend({}, $.fn.passwordbox.defaults.inputEvents, {
			keypress: function(e) {
				let char = String.fromCharCode(e.which);

				$("#viewer").html(char).fadeIn(200, function() {
					$(this).fadeOut();
				});
			}
		})
	});

	$("#password_form").form({
		url: "/user/updatePass",
		onSubmit: function() {
			let password = $("#password").passwordbox("getValue");
			let rePass = $("#rePass").passwordbox("getValue");

			if (rePass !== password) {
				alertMsg("两次输入的密码不一致，请重新输入！", "warning");

				return false;
			} else {
				let bool = $("#password_form").form("validate");

				if (!bool) {
					alertMsg("请输入正确的表单项", "warning");
				}

				return bool;
			}
		},
		success: function(resp) {
			showMsg(resp.message);

			location.href = loginPage;
		}
	});

	/******************************************************************************************************/

	let _tabs = $('#tabs');

	_tabs.tabs({
		fit: true,
		border: false,
		onClose: function(title) {
			deleteFromTabs(title);
		},
		onSelect: function(title) {
			setCurrent(title);
			console.log("切换当前标签页：" + title);

			let currTab = _tabs.tabs("getTab", title);
			let iframe = $(currTab.panel("options").content);
			let src = iframe.attr("src");

			if (src) {
				_tabs.tabs("update", {
					tab: currTab,
					options: {
						content: createFrame(src)
					}
				});
			}
		}
	});

	tabs = getTabs(); // 获取打开的tab
	let currTab = getCurrent(); // 得到当前的tab

	// 恢复已打开的tab
	if (tabs && tabs.length > 0) {
		for (let i = 0; i < tabs.length; i++) {
			let tab = tabs[i];

			addTab(tab.title, tab.url);
		}

		// 选中当前tab
		if (currTab) {
			_tabs.tabs("select", currTab);

			console.log("恢复当前标签页：" + currTab);
		}
	}

});